<template>
  <contentModel
    title="选择商务合同明细"
    class="add-detail-dialog"
    @close="closed"
  >
    <div style="height: 100%">
      <query-page
        ref="contractDetailPageRef"
        v-model:selectedKeys="selectedKeys"
        :form-component-config="formComponentConfig"
        :form-render-config="newformRenderConfig"
        :form-render-keys="formRenderKeys"
        :table-component-config="tableComponentConfig"
        :table-render-config="tableRenderConfig"
        :table-render-keys="tableRenderKeys"
        :loading="isLoading"
        :data="renderData"
        :total="total"
        row-selection-type="checkbox"
        @selection-change="selectionChange"
        @query-data="getData"
      >
        <template #top-container>
          <p-tabs
            v-model:value="activeTab"
            :is-show-num="false"
            :tab-list="materialType"
          />
        </template>
      </query-page>
    </div>
    <template #footer>
      <a-button @click="closed">{{ '取消' }}</a-button>
      <a-button type="primary" :disabled="importLoading" @click="save">{{
        '确定'
      }}</a-button>
    </template>
  </contentModel>
</template>

<script setup lang="ts">
  import {
    ref,
    defineProps,
    onMounted,
    defineEmits,
    watch,
    nextTick,
  } from 'vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import contentModel from '@/common/components/content-model/index.vue';
  import lodash from 'lodash';
  import {
    formRenderConfig,
    formComponentConfig,
  } from '@/views/purchase-order/components/formComp/baseFormDialogConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '@/views/purchase-order/components/tableComp/baseTableDialogConfig';
  import {
    getContractDetailPage,
    saveOrderDetailAll,
  } from '@/api/purchase-order/purchaseOrderPreparation';
  import { materialType } from '@/config/const';
  import { Message } from '@arco-design/web-vue';
  import pTabs from '../../components/p-tabs.vue';
  import { addDetailRenderKeys, itemReflection } from './config';

  const emit = defineEmits(['closeDrawer', 'success']);
  const props = defineProps({
    formInfo: {
      type: Object,
      default: null,
    },
    idList: {
      type: Array,
      default: () => [],
    },
  });
  const newformRenderConfig = ref({});
  newformRenderConfig.value = formRenderConfig(
    props.formInfo.orderNo,
    props.formInfo.mdsVendorName
  );
  const activeTab = ref('2');

  const contractDetailPageRef = ref();
  const importLoading = ref<boolean>(false);
  // const visible = ref(true);
  const selectedKeys = ref([]);
  const selection = ref<any[]>([]);
  const total = ref(0);
  // 渲染检索项
  const formRenderKeys = ref<any[]>([...addDetailRenderKeys.formRenderKeys]);
  // 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([...addDetailRenderKeys['1']]);
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  const getData = async (queryInfo: object) => {
    renderData.value = [];
    isLoading.value = true;
    const param: any = { ...queryInfo };
    param.mdsItemType = activeTab.value ? activeTab.value : '2';
    if (props.formInfo.orderNo) {
      param.contractCode = props.formInfo.orderNo;
    }
    if (props.formInfo.mdsVendorName) {
      param.supplierName = props.formInfo.mdsVendorName;
    }
    if (props.idList.length > 0) {
      param.idList = props.idList.join();
    }
    param.secretLevel = props.formInfo.secretLevel;
    const res: any = await getContractDetailPage(param);
    if (res.code === 200) {
      total.value = res.data.total;
      renderData.value = [...res.data.list];
    }
    isLoading.value = false;
    isLoading.value = false;
  };
  const selectionChange = (val: string[]) => {
    console.log('selectedKeys', val);
    selection.value = renderData.value.filter((item: any) => {
      return selectedKeys.value.includes(item.id);
    });
  };
  onMounted(() => {
    console.log('', props);
  });
  // 保存
  const save = async () => {
    if (selection.value.length === 0) {
      Message.warning('请先选择数据！');
      return;
    }
    const param = getParams();
    importLoading.value = true;
    try {
      const res: any = await saveOrderDetailAll(param);
      if (res.code === 200) {
        Message.success('添加成功');
        emit('success');
      }
    } finally {
      importLoading.value = false;
    }
  };
  interface Tst {
    [index: string]: any;
  }
  const tempVal = ref<Tst>({
    tempName11: 0,
    tempName12: 0,
    tempName13: 0,
    // tempName32: '2024-03-22',
    tempName20: 0,
    tempName21: 0,
    tempName22: 0,
    tempName23: '1',
    tempName29: 0,
    tempName30: 0,
  });
  // 数据整合
  const getParams = () => {
    const arr = selection.value.map((item) => {
      // const temp =
      item.pmsOrderId = props.formInfo.id;
      item.sysOrderNo = props.formInfo.sysOrderNo;
      Object.keys(itemReflection).forEach((key) => {
        if (item[itemReflection[key]] || item[itemReflection[key]] === 0) {
          item[key] = item[itemReflection[key]];
        } else {
          item[key] = lodash.get(tempVal.value, itemReflection[key], null);
        }
      });
      delete item.updater;
      return item;
    });
    return arr;
  };
  // 取消
  const closed = () => {
    emit('closeDrawer');
  };
  // 获取渲染表格得keys
  const getTableRenderKeys = () => {
    tableRenderKeys.value = [...addDetailRenderKeys[activeTab.value]];
  };
  watch(activeTab, () => {
    getTableRenderKeys();
    nextTick(() => {
      contractDetailPageRef.value?.formReset();
      selection.value = [];
      selectedKeys.value = [];
      getData(contractDetailPageRef.value.getStatus());
    });
  });
</script>

<style lang="less" scoped>
  .step-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 64px;
    margin-bottom: 16px;
    padding: 0 16px;
    background: #f7f9fc;
    border-radius: 8px;

    :deep(.arco-steps) {
      width: 100%;

      .arco-steps-item {
        border: 1px solid #d9dee7;

        &::after {
          display: none;
        }

        .arco-steps-item-node {
          display: none;
        }

        .arco-steps-item-content {
          margin-bottom: 0;
        }
      }
    }
  }
</style>

<style lang="less">
  .add-detail-dialog {
    .content-con {
      padding: 0 !important;

      .query-page-height {
        height: calc(100% - 64px) !important;
      }
    }
  }
</style>
